
TOOL.Category = '(Shanjaq)'
TOOL.Name = '#Environmental Control'
TOOL.Command = nil
TOOL.ConfigName = ''

TOOL.ClientConVar['type'] = 'air_tank'

TOOL.ClientConVar['model'] = 'models/props_combine/combine_emitter01.mdl'

cleanup.Register('lifesupport')
cleanup.Register( 'tankconstraints' )


if ( CLIENT ) then
	language.Add( 'Tool_life_support_name', 'Life Support Systems (Shanjaq)' )
	language.Add( 'Tool_life_support_desc', 'Create Life Support Systems attached to any surface.' )
	language.Add( 'Tool_life_support_0', 'Left-Click: Spawn a Device.  Right-Click: Repair Device.' )

	language.Add( 'Undone_LifeSupport', 'Life Support Device Undone' )
	language.Add( 'Undone_Hose', 'Air Conduit Undone' )
	language.Add( 'Cleanup_airtanks', 'Air Tank' )
	language.Add( 'Cleaned_airtank', 'Cleaned up all Life Support Devices' )
	language.Add( 'SBoxLimit_lifesupports', 'Maximum Life Support Devices Reached' )
end

if ( GAMEMODE.Name == "SpaceBuild" || SpaceBuild ) then 
	lifesupport_models = {
		{ 'Suit Dispenser', 'models/props_combine/combine_emitter01.mdl', 'dispenser' },
		{ 'Small Air Exchanger', 'models/props_combine/combine_light001a.mdl', 'air_exchanger' },
		{ 'Large Air Exchanger', 'models/props_combine/combine_light001b.mdl', 'air_exchanger' },
		{ 'Small Heat Exchanger', 'models/props_c17/utilityconnecter006c.mdl', 'heat_exchanger' },
		{ 'Large Heat Exchanger', 'models/props_c17/substation_transformer01d.mdl', 'heat_exchanger' },
		{ 'Climate Regulator', 'models/props_combine/combine_generator01.mdl', 'climate_control' },
		{ 'Atmospheric Probe', 'models/props_combine/combine_mine01.mdl', 'env_probe' },
		{ 'Air Hydroponics', 'models/props/cs_office/plant01.mdl', 'air_hydro' }
	}
else
	lifesupport_models = {
		{ 'Suit Dispenser', 'models/props_combine/combine_emitter01.mdl', 'dispenser' },
		{ 'Small Air Exchanger', 'models/props_combine/combine_light001a.mdl', 'air_exchanger' },
		{ 'Large Air Exchanger', 'models/props_combine/combine_light001b.mdl', 'air_exchanger' }
	
	}
end
--models/props_trainstation/TrackLight01.mdl
--models/props_combine/combine_generator01.mdl
--models/props_c17/utilityconnecter006c.mdl
--models/props_c17/substation_transformer01d.mdl
--models/props_lab/reciever01d.mdl
--models/props_lab/cactus.mdl
--models/props/cs_office/plant01.mdl
--models/Items/combine_rifle_ammo01.mdl
--models/props/CS_militia/tree_large_militia.mdl
function TOOL:LeftClick( trace )
	if trace.Entity && (trace.Entity:IsPlayer() ) then return false end
	
	if(CLIENT) then
		return true
	end

	if(!SERVER) then return false end

	if ( !self:GetSWEP():CheckLimit( "lifesupports" ) ) then return false end

	local ply = self:GetOwner()
	local Pos = trace.HitPos
	local Ang = trace.HitNormal:Angle()
	Ang.pitch = Ang.pitch + 90
	
	local life_support_type		= self:GetClientInfo('type')
	local life_support_model	= self:GetClientInfo('model')
	ent = MakeLifeSupport( ply, Ang, Pos, life_support_type, life_support_model )
	ent:SetPos( trace.HitPos - trace.HitNormal * ent:OBBMins().z)
	
	if ( trace.Entity:IsValid() ) then
		local const = constraint.Weld(ent, trace.Entity,0, trace.PhysicsBone, 0, systemmanager )
		nocollide = constraint.NoCollide( ent, trace.Entity, 0, trace.PhysicsBone )
		trace.Entity:DeleteOnRemove( ent )
	end

	undo.Create('LifeSupport')
		undo.AddEntity( ent)
		undo.AddEntity( const )
		undo.AddEntity( nocollide )
		undo.SetPlayer( ply )
	undo.Finish()


	ply:AddCleanup( 'lifesupport', const )
	ply:AddCleanup( 'lifesupport', nocollide )
	
	return true
end



function TOOL:RightClick( trace )
	if (not trace.Entity:GetTable().Repair) then
        self:GetOwner():SendLua( "GAMEMODE:AddNotify('Object cannot be repaired!', NOTIFY_GENERIC, 7);" )
		return
	end
	trace.Entity:Repair()
	return true
end


function TOOL:Reload(trace)
	return true
end




if SERVER then 
    CreateConVar('sbox_maxlifesupports',24)
	
	function MakeLifeSupport( ply, Ang, Pos, life_support_type, model )
		if ( !ply:CheckLimit( "lifesupports" ) ) then return nil end
		if not ( RES_DISTRIB == 1 ) then
			ply:PrintMessage( HUD_PRINTCENTER, "Please Install Resource Distribution Addon.\nThis mod requires it to function.\nSearch GarrysMod.org for 'distribution'" )  
			return
		end
		local ent = ents.Create( life_support_type )
			if !ent:IsValid() then return false end
			ent:SetModel( model )
			ent:SetAngles(Ang)
			ent:SetPos(Pos)
		ent:Spawn()

		ent:SetVar('Owner',ply)
		
		local phys = ent:GetPhysicsObject()
		local Active = 0
		local range = 0
		local max_health = 0
		local NextThink = CurTime() +  1
		if ( life_support_type == "dispenser" ) then
			max_health = 300
			RD_AddResource(ent, "air", 0)
			RD_AddResource(ent, "energy", 0)
			RD_AddResource(ent, "coolant", 0)
			local rtable = {
				life_support_type = life_support_type,
				model = model,
				max_health = max_health,
				health = max_health
				}
				
				
			table.Merge(ent:GetTable(), rtable )
--			duplicator.RegisterEntityClass( 'dispenser', MakeLifeSupport,  'Ang', 'Pos', 'life_support_type', 'model' )
		elseif ( life_support_type == "air_exchanger" ) then
			if (model == "models/props_combine/combine_light001a.mdl") then
				range = 250
				max_health = 500
				if (phys:IsValid()) then phys:SetMass(100) end
			elseif (model == "models/props_combine/combine_light001b.mdl") then
				range = 800
				max_health = 600
				if (phys:IsValid()) then phys:SetMass(800) end
			end
			RD_AddResource(ent, "air", 0)
			RD_AddResource(ent, "energy", 0)
			
			local rtable = {
				life_support_type = life_support_type,
				model = model,
				range = range,
				Active = Active,
				running = 0,
				max_health = max_health,
				health = max_health,
				NextThink = NextThink
				}
				
				
			table.Merge(ent:GetTable(), rtable )
--			duplicator.RegisterEntityClass( 'air_exchanger', MakeLifeSupport,  'Ang', 'Pos', 'life_support_type', 'model' )
		elseif ( life_support_type == "heat_exchanger" ) then
			if (model == "models/props_c17/utilityconnecter006c.mdl") then
				range = 250
				max_health = 500
				if (phys:IsValid()) then phys:SetMass(100) end
			elseif (model == "models/props_c17/substation_transformer01d.mdl") then
				range = 800
				max_health = 600
				if (phys:IsValid()) then phys:SetMass(1200) end
			end
			RD_AddResource(ent, "energy", 0)
			RD_AddResource(ent, "coolant", 0)
			
			local rtable = {
				life_support_type = life_support_type,
				model = model,
				range = range,
				temperature = FairTemp,
				atmosphere = 1,
				Active = Active,
				running = 0,
				max_health = max_health,
				health = max_health,
				NextThink = NextThink
				}
				
				
			table.Merge(ent:GetTable(), rtable )
--			duplicator.RegisterEntityClass( 'heat_exchanger', MakeLifeSupport,  'Ang', 'Pos', 'life_support_type', 'model' )
		elseif ( life_support_type == "climate_control" ) then
			range = 1200
			max_health = 700
			if (phys:IsValid()) then phys:SetMass(1200) end
			RD_AddResource(ent, "air", 0)
			RD_AddResource(ent, "energy", 0)
			RD_AddResource(ent, "coolant", 0)
			
			local rtable = {
				life_support_type = life_support_type,
				model = model,
				range = range,
				temperature = FairTemp,
				atmosphere = 1,
				Active = Active,
				air_running = 0,
				heat_running = 0,
				max_health = max_health,
				health = max_health,
				NextThink = NextThink
				}
				
				
			table.Merge(ent:GetTable(), rtable )
--			duplicator.RegisterEntityClass( 'heat_exchanger', MakeLifeSupport,  'Ang', 'Pos', 'life_support_type', 'model' )
		elseif ( life_support_type == "env_probe" ) then
			max_health = 400
			RD_AddResource(ent, "energy", 0)
			
			local rtable = {
				life_support_type = life_support_type,
				model = model,
				habitat = 1,
				temperature = FairTemp,
				atmosphere = 1,
				Active = Active,
				running = 0,
				max_health = max_health,
				health = max_health,
				NextThink = NextThink
				}
				
				
			table.Merge(ent:GetTable(), rtable )
--			duplicator.RegisterEntityClass( 'env_probe', MakeLifeSupport,  'Ang', 'Pos', 'life_support_type', 'model' )
		elseif ( life_support_type == "air_hydro" ) then
			range = 800
			max_health = 400
			local rtable = {
				life_support_type = life_support_type,
				model = model,
				max_health = max_health,
				health = max_health,
				range = range,
				NextThink = NextThink
				}
				
				
			table.Merge(ent:GetTable(), rtable )
--			duplicator.RegisterEntityClass( 'air_hydro', MakeLifeSupport,  'Ang', 'Pos', 'life_support_type', 'model' )
		end
		
		if ent:GetTable().OnTakeDamage then
			local Prev = ent:GetTable().OnTakeDamage
			
			function ent:OnTakeDamage(Info)
				DamageLS(self, Info:GetDamage())
				Prev(self, Info)
			end
		end
		
		ply:AddCount('lifesupports', ent)
		
		return ent
	end
	duplicator.RegisterEntityClass("air_exchanger", MakeLifeSupport, "Ang", "Pos", "life_support_type", "model", "Vel", "aVel", "frozen")
	duplicator.RegisterEntityClass("heat_exchanger", MakeLifeSupport, "Ang", "Pos", "life_support_type", "model", "Vel", "aVel", "frozen")
	duplicator.RegisterEntityClass("climate_control", MakeLifeSupport, "Ang", "Pos", "life_support_type", "model", "Vel", "aVel", "frozen")
	duplicator.RegisterEntityClass("env_probe", MakeLifeSupport, "Ang", "Pos", "life_support_type", "model", "Vel", "aVel", "frozen")
	duplicator.RegisterEntityClass("dispenser", MakeLifeSupport, "Ang", "Pos", "life_support_type", "model", "Vel", "aVel", "frozen")
	duplicator.RegisterEntityClass("air_hydro", MakeLifeSupport, "Ang", "Pos", "life_support_type", "model", "Vel", "aVel", "frozen")

	
end

function TOOL.BuildCPanel( cp )
	cp:AddControl( 'Header', { Text = '#Tool_life_support_name', Description	= '#Tool_life_support_desc' }  )

	local combo = {}
	combo.Label = 'Life Support Device'
	combo.MenuButton = 1
	combo.Folder = 'settings/menu/main/construct/lifesupport/'
	combo.Options = {}
	
	for k, v in pairs(lifesupport_models) do
	  combo.Options[v[1]] = { life_support_model = v[2], life_support_type = v[3] }
	end

	cp:AddControl('ComboBox', combo) 

end

function TOOL:UpdateGhostLifeSupport( ent, player )

	if ( !ent ) then return end
	if ( !ent:IsValid() ) then return end

	local tr 	= utilx.GetPlayerTrace( player, player:GetCursorAimVector() )
	local trace 	= util.TraceLine( tr )
	if (!trace.Hit) then return end
	
	if (trace.Entity && trace.Entity:GetClass() == "air_tank" || trace.Entity:IsPlayer() ) then
	
		ent:SetNoDraw( true )
		return
		
	end
	
--	local ang = player:GetAimVector():Angle() 
--	ent:SetAngles(Angle(0,ang.Yaw,0))
	local Ang = trace.HitNormal:Angle()
	Ang.pitch = Ang.pitch + 90
	ent:SetAngles( Ang )
	
	local min = ent:OBBMins()
	ent:SetPos( trace.HitPos - trace.HitNormal * min.z )
	
	ent:SetNoDraw( false )
	
end


function TOOL:Think()
	local model	= self:GetClientInfo('model')
	
	if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != model) then
		self:MakeGhostEntity( model, Vector(0,0,0), Angle(0,0,0) )
	end
	
	self:UpdateGhostLifeSupport( self.GhostEntity, self:GetOwner() )
end


